<?php

namespace App\Http\Controllers\Entity\Column;

use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Column\RecommendRequest;
use App\Jobs\Publish\RecommendJob;
use App\Models\Common\CatData\Video\Vcat;
use App\Models\Common\TagData\Video\Vcattag;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Column\Collist;
use App\Models\Entity\Column\Column;
use App\Models\Entity\Column\Recommend;
use App\Models\Entity\Column\RecommendVasseti;
use App\Models\Task\Task;
use App\Repositories\Entity\Column\RecommendRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;

class RecommendController extends Controller
{
    use ModelForm;

    /** @var  RecommendRepository */
    private $recommendRepository;

    public function __construct(RecommendRepository $recommendRepo)
    {
        $this->recommendRepository = $recommendRepo;
    }

    /**
     * Display a listing of the Recommend.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('entity.column.recommends.index_header'));
            $content->description(__('entity.column.recommends.index_description'));

            $content->body($this->grid($request));
        });
    }

    /**
     * Show the form for creating a new Recommend.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.column.recommends.create_header'));
            $content->description(__('entity.column.recommends.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Recommend in storage.
     *
     * @param RecommendRequest $request
     *
     * @return Response
     */
    public function store(RecommendRequest $request)
    {
        $input                       = $request->all();
        $recommendData               = [];
        $recommendData['name']       = $input['name'];
        $recommendData['title']      = $input['title'];
        $recommendData['subtitle']   = $input['subtitle'];
        $recommendData['collist_id'] = $input['collist_id'];
        $recommendData['column_id']  = $input['column_id'];
        $recommendData['short_desc'] = $input['short_desc'];
        $recommendData['long_desc']  = $input['long_desc'];

        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.recommend');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;
                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['img'] = $rootDir . $fullPath;

                // $input['img'] = $fullPath;
                $recommendData['img'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $recommend      = $this->recommendRepository->create($recommendData);
        $recommendDatas = $input['recommenddata'];
        $recommendId    = $recommend->id;

        // 推荐位保存成功后包推荐位数据
        $datas = [];
        foreach ($recommendDatas as $key => $value) {
            $data = [];
            if ($value['_remove_'] != '1') {
                $data['recommend_id'] = $recommendId;
                $data['name']         = $value['name'];
                $data['title']        = $value['title'];
                $data['subtitle']     = $value['subtitle'];
                $data['href']         = $value['href'];
                $datas[]              = $data;
            }
        }

        $insertStatus = DB::table('recommend_datas')->insert($datas);
        if (empty($insertStatus)) {
            Flash::error('推荐模板数据插入失败');
            return redirect(route('entity.column.recommends.index'));
        }

        Flash::success(__('entity.column.recommends.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.column.recommends.index'));

    }

    /**
     * Display the specified Recommend.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $recommend = $this->recommendRepository->findWithoutFail($id);

        if (empty($recommend)) {
            Flash::error(__('entity.column.recommends.not_found'));

            return redirect(route('entity.column.recommends.index'));
        }

        return view('entity.column.recommends.show')->with('recommend', $recommend);

    }

    /**
     * Show the form for editing the specified Recommend.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.column.recommends.edit_header'));
            $content->description(__('entity.column.recommends.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Recommend in storage.
     *
     * @param  int              $id
     * @param RecommendRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $recommend = $this->recommendRepository->findWithoutFail($id);

        if (empty($recommend)) {
            Flash::error(__('entity.column.recommends.not_found'));

            return redirect(route('entity.column.recommends.index'));
        }

        $input                       = $request->all();
        $recommendData               = [];
        $recommendData['name']       = $input['name'];
        $recommendData['title']      = $input['title'];
        $recommendData['subtitle']   = $input['subtitle'];
        $recommendData['collist_id'] = $input['collist_id'];
        $recommendData['column_id']  = $input['column_id'];
        $recommendData['short_desc'] = $input['short_desc'];
        $recommendData['long_desc']  = $input['long_desc'];
        if (array_key_exists('_file_del_', $input)) {

            $imgUrl       = $recommend->img;
            $uploadConfig = config('custom.base.upload.recommend');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];

            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                // $recommend->img = null;
                // $recommend->save();
                return response()->json(['message' => '图片删除成功!', 'status' => $flag]);
            }

            return response()->json(['message' => '图片删除失败!', 'status' => $flag]);
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), [
            // 'recommend_no' => 'required|max:100|unique:recommends,recommend_no,' . $id,
            'name'       => 'required|max:100',
            'title'      => 'max:100',
            'subtitle'   => 'max:100',
            'collist_id' => 'required|max:100',
            'column_id'  => 'required|max:100',
            // 'img'          => 'required', // |max:200
            'short_desc' => 'max:100',
        ], [
            // 'required' => ':attribute 不能为空',
        ], [
            // 'name'       => '名称',
        ]);

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.recommend');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['img'] = $rootDir . $fullPath;

                // $input['img'] = $fullPath;
                $recommendData['img'] = $fullPath;

                // 2017/08/22 modify
                // 删除原先存储的图片
                $flag = Storage::disk($driver)->delete($recommend->img);

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $recommend = $this->recommendRepository->update($recommendData, $id);

        $recommendDatas = $input['recommenddata'];
        // 推荐位保存成功后包推荐位数据
        $datas = [];
        foreach ($recommendDatas as $key => $value) {
            $data = [];
            if ($value['_remove_'] != '1') {
                $data['recommend_id'] = $id;
                $data['name']         = $value['name'];
                $data['title']        = $value['title'];
                $data['subtitle']     = $value['subtitle'];
                $data['href']         = $value['href'];
                $datas[]              = $data;
            }
        }
        DB::beginTransaction();
        try {
            DB::table('recommend_datas')->where('recommend_id', $id)->delete();
            DB::table('recommend_datas')->insert($datas);
            DB::commit();
        } catch (Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            throw $e;
        }

        Flash::success(__('entity.column.recommends.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.column.recommends.index'));
    }

    /**
     * Remove the specified Recommend from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        } else {
            // 只有下线且下线发布的才能删除
            $recommend = Recommend::where('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->first();
            if (empty($recommend)) {
                return response()->json(['message' => '只有状态为下线且已下线发布的才可以删除', 'status' => false]);
            }
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            // 只有下线且下线发布的才能删除
            $id = Recommend::whereIn('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->pluck('id')->toArray();
            if ($flag = $this->recommendRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('entity.column.recommends.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => '只有状态下线发布的才可以删除', 'status' => $flag]);
            }
        }

        $recommend = $this->recommendRepository->findWithoutFail($id);

        if (empty($recommend)) {
            Flash::error(__('entity.column.recommends.not_found'));

            return redirect(route('entity.column.recommends.index'));
        }

        // 2017/08/22 modify
        // $imgUrl       = $recommend->img;
        // $uploadConfig = config('custom.base.upload.recommend');
        // $driver       = $uploadConfig['driver'];
        // $dir          = $uploadConfig['dir'];

        // 根据配置得到根路径
        // $rootDir = config('filesystems.disks.' . $driver . '.upload');

        // $rootDir  = config('filesystems.disks.'.$driver.'.root');
        // $imgUrl = strchr($imgUrl, $rootDir);

        if ($flag = $this->recommendRepository->delete($id)) {

            // 2017/08/22 modify
            // $bool = Storage::disk($driver)->delete($imgUrl);

            $recommend->vassetis()->detach();

            return response()->json(['message' => __('entity.column.recommends.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [editAsset 编辑媒资界面]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function editAsset($id)
    {
        $recommend = $this->recommendRepository->findWithoutFail($id);

        if (empty($recommend)) {
            Flash::error(__('entity.column.recommends.not_found'));

            return redirect(route('entity.column.recommends.index'));
        }

        // 只能手动调用下函数
        Admin::script('entityColumnRecommendAsset();');
        // 分类
        $vcats = Vcat::get(['name', 'id']);
        // 归类数据
        $vcattags = Vcattag::get(['name', 'id']);
        return view('entity.column.recommend.asset', ['vcats' => $vcats, 'vcattags' => $vcattags, 'recommend_id' => $id]);
    }

    /**
     * [selected 已选的媒资数据]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function selected(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vcat = $request->input('vcat');
            // 分类
            $vcattag = $request->input('vcattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 推荐位id
            $recommend_id = $request->input('recommend_id');

            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = RecommendVasseti::whereHas('recommend', function ($query) use ($recommend_id) {
                if (!empty($recommend_id)) {
                    $query = $query->where('id', '=', $recommend_id);
                }
            })->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }
            $data['recordsFiltered'] = RecommendVasseti::with(['recommend', 'vasseti', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('recommend', function ($query) use ($recommend_id) {
                    if (!empty($recommend_id)) {
                        $query = $query->where('id', '=', $recommend_id);
                    }
                })
                ->whereHas('vasseti', function ($query) use ($search_value) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                })->count();

            $data['data'] = RecommendVasseti::with(['recommend', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('recommend', function ($query) use ($recommend_id) {
                    if (!empty($recommend_id)) {
                        $query = $query->where('id', '=', $recommend_id);
                    }
                })
                ->whereHas('vasseti', function ($query) use ($search_value) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();
            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * [data 媒资数据]
     * @return [type] [description]
     */
    public function data(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vcat = $request->input('vcat');
            // 分类
            $vcattag = $request->input('vcattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 推荐位id
            $recommend_id = $request->input('recommend_id');

            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = Vasseti::onlineStatus()->onlinePublished()->
                where(function ($query) use ($recommend_id) {
                if (!empty($recommend_id)) {
                    $query = $query->whereNotIn('id', RecommendVasseti::where(['recommend_id' => $recommend_id])->pluck('vasseti_id')->toArray());
                }
            })
                ->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }

            $data['recordsFiltered'] = Vasseti::onlineStatus()->onlinePublished()->with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'])
                ->whereHas('vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->where(function ($query) use ($search_value, $recommend_id) {
                    if (!empty($search_value)) {
                        $query = $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($recommend_id)) {
                        $query = $query->whereNotIn('id', RecommendVasseti::where(['recommend_id' => $recommend_id])->pluck('vasseti_id')->toArray());
                    }
                })->count();

            $data['data'] = Vasseti::onlineStatus()->onlinePublished()->with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'])
                ->whereHas('vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->where(function ($query) use ($search_value, $recommend_id) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($recommend_id)) {
                        $query = $query->whereNotIn('id', RecommendVasseti::where(['recommend_id' => $recommend_id])->pluck('vasseti_id')->toArray());
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();

            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * 添加单个媒资|多个媒资
     * @param Request $request [description]
     */
    public function addVasseti(Request $request)
    {
        $recommend_id = $request->input('recommend_id');
        $vasseti_id   = $request->input('vasseti_id');

        // 如果推荐位已经上线且发布,则不让新增、删除操作
        $data = Recommend::where('id', '=', $recommend_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该推荐位已上线发布,不能添加媒资!', 'status' => false]);
        }

        if (empty($recommend_id)) {
            return response()->json(['content' => '推荐位为空!', 'status' => false]);
        }
        if (empty($vasseti_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量添加
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $value) {
                $flag = RecommendVasseti::where(['recommend_id' => $recommend_id, 'vasseti_id' => $value])->first();
                if ($flag) {
                    return response()->json(['content' => '不能重复添加已经存在的媒资!', 'status' => false]);
                } else {
                    $recommendVasseti               = new RecommendVasseti();
                    $recommendVasseti->recommend_id = $recommend_id;
                    $recommendVasseti->vasseti_id   = $value;
                    if (!$recommendVasseti->save()) {
                        return response()->json(['content' => '添加失败!', 'status' => false]);
                    }
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }

        $flag = RecommendVasseti::where(['recommend_id' => $recommend_id, 'vasseti_id' => $vasseti_id])->first();
        if ($flag) {
            return response()->json(['content' => '该媒资已经存在,不能重复添加!', 'status' => false]);
        } else {
            $recommendVasseti               = new RecommendVasseti();
            $recommendVasseti->recommend_id = $recommend_id;
            $recommendVasseti->vasseti_id   = $vasseti_id;
            $flag                           = $recommendVasseti->save();
            if ($flag) {
                return response()->json(['content' => '添加成功!', 'status' => $flag]);
            } else {
                return response()->json(['content' => '添加失败!', 'status' => $flag]);
            }
        }
    }

    /**
     * 删除单个媒资|多个媒资
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function deleteVasseti(Request $request)
    {
        $recommend_id = $request->input('recommend_id');
        $vasseti_id   = $request->input('vasseti_id');

        // 如果推荐位已经上线且发布,则不让新增、删除操作
        $data = Recommend::where('id', '=', $recommend_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该推荐位已上线发布,不能删除媒资!', 'status' => false]);
        }

        if (empty($recommend_id)) {
            return response()->json(['content' => '推荐位为空!', 'status' => false]);
        }
        if (empty($vasseti_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量删除
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $value) {
                $flag = RecommendVasseti::where(['recommend_id' => $recommend_id, 'vasseti_id' => $value])->delete();

                if (!$flag) {
                    return response()->json(['content' => '删除失败!', 'status' => $flag]);
                }
            }
            return response()->json(['content' => '删除成功!', 'status' => true]);
        }

        $flag = RecommendVasseti::where(['recommend_id' => $recommend_id, 'vasseti_id' => $vasseti_id])->delete();

        if ($flag) {
            return response()->json(['content' => '删除成功!', 'status' => $flag]);
        } else {
            return response()->json(['content' => '删除失败!', 'status' => $flag]);

        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Recommend::class, function (Form $form) {
            $form->tab('基本数据', function ($form) {
                $form->display('id', 'ID');
                $form->text('name', '名称');
                $form->text('title', '标题');
                $form->text('subtitle', '副标题');
                $collists = Collist::pluck('name', 'id');
                $form->select('collist_id', '栏目列表')->options($collists);
                $columns = Column::pluck('name', 'id');
                $form->select('column_id', '栏目')->options($columns);
                $form->image('img', 'banner图')->removable();
                $form->text('short_desc', '简介');
                $form->textarea('long_desc', '详述');
                $form->display('created_at', __('base.created_at'));
                $form->display('updated_at', __('base.updated_at'));
            })->tab('推荐数据', function ($form) {
                // layout布局
                $form->hasMany('recommenddata', '新增推荐数据', function (Form\NestedForm $form) {
                    $form->text('name', '名称');
                    $form->text('title', '标题');
                    $form->text('subtitle', '副标题');
                    $form->text('href', '链接地址');
                })->rules("required");
            });
        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {

        return Admin::grid(Recommend::class, function (Grid $grid) use ($request) {

            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // 状态过滤
            $fields = ['all', 'on', 'off'];
            if (in_array($request->input('status'), $fields) && in_array($request->input('published'), $fields)) {
                switch ($request->input('status')) {
                    case 'all':
                        switch ($request->input('published')) {
                            case 'all':
                                break;
                            case 'on':
                                $grid->model()->where(['publish_status' => 1])->orWhere(['publish_down_status' => 1]);
                                break;
                            case 'off':
                                $grid->model()->where(['online_status' => 1, 'publish_status' => 0])
                                    ->orWhere(['online_status' => 0, 'publish_down_status' => 0]);
                                break;
                        }
                        break;
                    case 'on':
                        switch ($request->input('published')) {
                            case 'all':
                                $grid->model()->where(['online_status' => 1]);
                                break;
                            case 'on':
                                $grid->model()->where(['online_status' => 1, 'publish_status' => 1]);
                                break;
                            case 'off':
                                $grid->model()->where(['online_status' => 1, 'publish_status' => 0]);
                                break;
                        }
                        break;
                    case 'off':
                        switch ($request->input('published')) {
                            case 'all':
                                $grid->model()->where(['online_status' => 0]);
                                break;
                            case 'on':
                                $grid->model()->where(['online_status' => 0, 'publish_down_status' => 1]);
                                break;
                            case 'off':
                                $grid->model()->where(['online_status' => 0, 'publish_down_status' => 0]);
                                break;
                        }
                        break;
                }
            }

            // //添加按钮
            // if (!\Gate::check('entity.column.recommends.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('entity.column.recommends.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('entity.column.recommends.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('entity.column.recommends.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('entity.column.recommends.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 表格中的按钮
            $grid->actions(function ($actions) {
                $publish_down_status = $actions->row->publish_down_status;
                $publish_status      = $actions->row->publish_status;
                $online_status       = $actions->row->online_status;
                $id                  = $actions->getKey();
                $url                 = route('entity.column.recommends.up');
                $functionUp          = "upAndDownByOne('$url', 'post', {ids: [$id],action: 1,_token: LA.token})";
                $url                 = route('entity.column.recommends.down');
                $functionDown        = "upAndDownByOne('$url', 'post', {ids: [$id],action: 2,_token: LA.token})";
                $url                 = route('entity.column.recommends.publish_one');
                $functionPublishUp   = "upAndDownByOne('$url', 'post', {ids: [$id],action: 3,_token: LA.token})";
                // 媒资编辑
                // if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.column.recommends.edit_asset')) {
                //     if (Admin::user()->can('entity.column.recommends.edit_asset')) {
                //         $url = route('entity.column.recommends.edit_asset', ['recommends' => $id]);
                //         $actions->prepend('<a href ="' . $url . '" title="编辑媒资"><i class="fa fa-list"></i></a>');
                //     }
                // }
                // 推荐位数据编辑
                // $url = route('entity.column.recommends.edit_asset', ['recommends' => $id]);
                // $actions->prepend('<a href ="' . $url . '" title="编辑推荐位数据"><i class="fa fa-list"></i></a>');
                // 上线按钮
                if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.column.recommends.up')) {
                    $actions->append('<a href="javascript:void(0)" onclick="' . $functionUp . '" title="上线"><i class="fa fa-arrow-up"></i></a>');
                }
                // 上线发布按钮
                if ($online_status === 1 && $publish_status === 0 && Admin::user()->can('entity.column.recommends.publish_one')) {
                    $actions->append('<a href="javascript:void(0)" onclick="' . $functionPublishUp . '" title="上线发布"><i class="glyphicon glyphicon-floppy-open"></i></a>');
                }
                // 下线按钮
                if ($online_status === 1 && Admin::user()->can('entity.column.recommends.down')) {
                    $actions->append('<a href="javascript:void(0)" onclick="' . $functionDown . '" title="下线"><i class="fa fa-arrow-down"></i></a>');
                }
                //编辑按钮
                if (Admin::user()->cannot('entity.column.recommends.edit')) {
                    $actions->disableEdit();
                }
                //删除按钮
                if (Admin::user()->cannot('entity.column.recommends.destroy')) {
                    $actions->disableDelete();
                }
                //只有状态下线的资源才可以编辑,删除
                if ($publish_down_status === 0) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                }
            });

            //添加按钮
            if (Admin::user()->cannot('entity.column.recommends.create')) {
                $grid->disableCreation();
            }

            //导出按钮
            if (Admin::user()->cannot('entity.column.recommends.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $url2 = route('entity.column.recommends.progress');
                // 下线发布功能
                if (Admin::user()->can('entity.column.recommends.publish_down')) {
                    $url      = route('entity.column.recommends.publish_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-download"></i>下线发布</a>');
                }
                // 上线发布功能
                if (Admin::user()->can('entity.column.recommends.publish')) {
                    $url      = route('entity.column.recommends.publish');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-upload"></i>上线发布</a>');
                }
                // 全部下线功能
                if (Admin::user()->can('entity.column.recommends.all_down')) {
                    $url      = route('entity.column.recommends.all_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-down"></i>全部下线</a>');
                }
                // 全部上线功能
                if (Admin::user()->can('entity.column.recommends.all_up')) {
                    $url      = route('entity.column.recommends.all_up');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-success pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-up"></i>全部上线</a>');
                }
                // 过滤按钮
                $tools->append(new \App\Admin\Extensions\Tools\Recommend\RecommendStatus());
                $tools->append(new \App\Admin\Extensions\Tools\Recommend\RecommendPublished());
                // 批量按钮
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.column.recommends.batch_destroy')) {
                        $batch->disableDelete();
                    }
                    // 批量上线按钮
                    if (Admin::user()->can('entity.column.recommends.up')) {
                        $batch->add('上线', new \App\Admin\Extensions\Tools\Recommend\ReleaseRecommend(1));
                    }
                    // 批量下线按钮
                    if (Admin::user()->can('entity.column.recommends.down')) {
                        $batch->add('下线', new \App\Admin\Extensions\Tools\Recommend\ReleaseRecommend(2));
                    }
                });
            });

            // $grid->column('recommend_no', '编号')->sortable();
            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('collist.name', '栏目列表')->sortable();
            $grid->column('column.name', '栏目')->sortable();
            $uploadConfig = config('custom.base.upload.recommend');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('img', 'banner图')->image($host);
            // 2017/08/23 tian modify 添加媒资为跳转编辑
            // $grid->vassetis('媒资')->pluck('name')->label();
            $grid->column('short_desc', '简介')->sortable();
            $grid->column('long_desc', '详述')->sortable();
            $grid->column('online_at', '上线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('offline_at', '下线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-red">下线</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">上线</span>';
                        break;
                    default:
                        return '未知';
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($this->online_status) {
                    case 0:
                        switch ($this->publish_down_status) {
                            case 0:
                                return '<span class="badge bg-red">下线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">下线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    case 1:
                        switch ($this->publish_status) {
                            case 0:
                                return '<span class="badge bg-red">上线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">上线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    default:
                        return '未知';
                }
            })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 所属栏目
                $tempColumns = Column::pluck('name', 'id');
                $filter->equal('column_id', '栏目')->select($tempColumns);
                // 编号
                // $filter->like('recommend_no', '编号');
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
            });
        });
    }

    /**
     * 全部上线功能
     */
    public function allUp()
    {
        if (Admin::user()->cannot('entity.column.recommends.all_up')) {
            self::myinfo('您的权限不够!');
            return;
        }
        $taskid = self::insertTasks(['task_type' => '专题上线', 'user_id' => Admin::user()->id]);
        dispatch(new RecommendJob(3, '', $taskid));
        return response()->json(['taskid' => $taskid]);
    }

    /**
     * 全部下线功能
     */
    public function allDown()
    {
        if (Admin::user()->cannot('entity.column.recommends.all_down')) {
            self::myinfo('您的权限不够!');
            return;
        }
        $taskid = self::insertTasks(['task_type' => '专题上线', 'user_id' => Admin::user()->id]);
        dispatch(new RecommendJob(5, '', $taskid));
        return response()->json(['taskid' => $taskid]);
    }

    /**
     * 上线发布功能,由于是全部发布,整个操作放入队列
     */
    public static function publish(Request $request)
    {
        if (Admin::user()->cannot('entity.column.recommends.publish')) {
            self::myinfo('您的权限不够!');
            return;
        }
        // 任务表插入一条记录
        $taskid = self::insertTasks(['task_type' => '专题上线发布', 'user_id' => Admin::user()->id]);
        dispatch(new RecommendJob(1, '', $taskid));
        return response()->json(['taskid' => $taskid]);
    }

    /**
     * 下线发布功能
     */
    public function publishDown(Request $request)
    {
        if (Admin::user()->cannot('entity.column.recommends.publish_down')) {
            self::myinfo('您的权限不够!');
            return;
        }
        // 任务表插入一条记录
        $taskid = self::insertTasks(['task_type' => '专题下线发布', 'user_id' => Admin::user()->id]);
        dispatch(new RecommendJob(7, '', $taskid));
        return response()->json(['taskid' => $taskid]);
    }

    /**
     * 批量上下线功能
     */
    public function batchModerate(Request $request)
    {
        $user_id = Admin::user()->id;
        switch ($request->action) {
            //上线操作
            case '1':
                if (Admin::user()->cannot('entity.column.recommends.up')) {
                    self::myinfo('您的权限不够!');
                    return;
                }
                $ids = self::myfilter($request->ids, ['online_status' => 0, 'publish_down_status' => 1]);
                if (empty($ids)) {
                    self::myinfo('所选资源状态不可做此操作!');
                    return;
                }
                $result = self::updateRecommends($ids, [
                    'online_status'       => 1,
                    'publish_down_status' => 0,
                    'user_id'             => $user_id,
                    'online_at'           => date('Y-m-d H:i:s'),
                ]);
                self::myinfo($result ? '上线成功!' : '上线失败!');
                break;
            //下线操作
            case '2':
                if (Admin::user()->cannot('entity.column.recommends.down')) {
                    self::myinfo('您的权限不够!');
                    return;
                }
                $ids = self::myfilter($request->ids, ['online_status' => 1]);
                if (empty($ids)) {
                    self::myinfo('所选资源状态不可做此操作!');
                    return;
                }
                $result = self::updateRecommends($ids, [
                    'online_status'  => 0,
                    'publish_status' => 0,
                    'user_id'        => $user_id,
                    'offline_at'     => date('Y-m-d H:i:s'),
                ]);
                self::myinfo($result ? '下线成功!' : '下线失败!');
                break;
            // 上线发布
            case '3':
                if (Admin::user()->cannot('entity.column.recommends.publish_one')) {
                    self::myinfo('您的权限不够!');
                    return;
                }
                $ids = self::myfilter($request->ids, ['online_status' => 1, 'publish_status' => 0]);
                if (empty($ids)) {
                    self::myinfo('所选资源状态不可做此操作!');
                    return;
                }
                // 获取需要发布的媒资数据
                $recommends = self::getRecommends($ids);
                $data       = [];
                $datas      = [];
                foreach ($recommends as $recommend_key => $recommend_value) {
                    // 推荐位ID
                    $data['recommend_id'] = $recommend_value->id;
                    // 专题名称
                    $data['name'] = $recommend_value->name;
                    // 专题标题
                    $data['title'] = $recommend_value->title;
                    // 副标题
                    $data['subtitle'] = $recommend_value->subtitle;
                    // 详情
                    $data['long_desc'] = $recommend_value->long_desc;
                    // 简述
                    $data['short_desc'] = $recommend_value->short_desc;
                    // 图片
                    $data['img'] = $recommend_value->img;
                    // 关联栏目列表
                    $data['collist_id'] = $recommend_value->collist_id;
                    // 关联栏目
                    $data['column_id'] = $recommend_value->column_id;
                    // 关联媒资
                    $data['vassetis'] = $recommend_value->vassetis->first() ? $recommend_value->vassetis->toJson() : '';
                    $datas[]          = $data;
                }
                // 接口库插入数据
                $result1 = self::insertRecommendsApi($datas);
                // 更新状态
                $result2 = self::updateRecommends($ids, [
                    'publish_status' => 1,
                    'user_id'        => $user_id,
                ]);
                self::myinfo($result1 && $result2 ? '上线发布成功!' : '上线发布失败!');
                break;
        }
    }

    /**
     * 通过ids获取数据库中的媒资数据
     */
    public static function getRecommends($ids)
    {
        try {
            return Recommend::with(['vassetis'])->whereIn('id', $ids)->get();
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 将数据插入到接口库中
     */
    public static function insertRecommendsApi($data)
    {
        try {
            return DB::connection('interface')->table('recommends')->insert($data);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 查询进度
     */
    public function queryProgress(Request $request)
    {
        $taskid = (int) $request->input('taskid');
        $data   = Task::where('id', $taskid)->first();
        if ($data->total_num === 0) {
            return response()->json(['percent' => '0%']);
        }
        if ($data->total_num === -1) {
            return response()->json(['percent' => '100%']);
        }
        return response()->json(['percent' => ceil($data->done_num * 100 / $data->total_num) . '%']);
    }

    /**
     * 下线删除接口库中对应媒资内容
     */
    public static function destroyRecommendsFromApiDB($ids)
    {
        try {
            return DB::connection('interface')->table('recommends')->whereIn('recommend_id', $ids)->delete();
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 筛选ids
     */
    public static function myfilter($ids, $filter)
    {
        try {
            return Recommend::whereIn('id', $ids)->where($filter)->pluck('id');
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 提示信息
     */
    public static function myinfo($info)
    {
        Flash::success($info);
        return redirect(route('entity.column.recommends.index'));
    }

    /**
     * 更新专题表
     */
    public static function updateRecommends($ids, $data)
    {
        try {
            return Recommend::whereIn('id', $ids)->update($data);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 获取一个任务id
     */
    public static function insertTasks($data)
    {
        try {
            return Task::insertGetId($data);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 更新任务表
     */
    public static function updateTasks($id, $data)
    {
        try {
            return Task::where('id', $id)->update($data);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }
}
